# -*- coding: utf-8 -*-
# 创建时间：2021/7/16 17:01
from bs4 import BeautifulSoup
import requests
import time, math, random, json
import pymysql
import re
import os
__author__ = 'LuckyHhy'


num = 1
numPicture=0


# 统计张数
def count_num(url, A):
    print('正在检测图片总数，请稍等.....')
    t = 0
    s = 0
    while t < 1000:
        URL = url.format(t)
        try:
            # 这里搞了下
            Result = A.get(URL, timeout=20, allow_redirects=False)
        except BaseException:
            t = t + 60
            continue
        else:
            result = Result.text
            pic_url = re.findall('"objURL":"(.*?)",', result, re.S)  # 先利用正则表达式找到图片url
            s += len(pic_url)
            if len(pic_url) == 0:
                break
            else:
                t = t + 60
    return s


# 下载图片
def DownLoadImg(url, A , numPicture,word):

    global num
    t = 0
    n = 0
    save_dir = 'D:\\pic\\{}\\'.format(word)
    # 创建保存文件夹
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    while t < 1000:  # 请求20次
        URL = url.format(t)
        Result = A.get(URL, timeout=20, allow_redirects=False)
        result = Result.text
        # result.encode("utf8")
        pic_url = re.findall('"objURL":"(.*?)",', result, re.S)  # 先利用正则表达式找到图片url
        n += len(pic_url)
        # 生成文件

        for i in pic_url:
            # name = ''.join(random.sample(string.ascii_letters + string.digits, 8))
            name = str(num)
            file_path = '{0}\\{1}.png'.format(save_dir, name)  #
            cont = A.get(i, timeout=20)
            print('正在下载第{0} 张图片地址：{1}'.format(num, i))
            with open(file_path, 'wb') as f:
                f.write(cont.content)  # 写入内容
                f.close()
                num += 1

            if num > numPicture:
                print("{0}张图片全部下载完成".format(numPicture))
                return

        t += 60  # 每页展示的是60张


USER_AGENTS = [
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
    "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
    "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
    "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
]


def main():
    headers = {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Connection': 'keep-alive',
        'User-Agent': random.choice(USER_AGENTS),
        'Content-Type': 'text/plain;charset=UTF-8',
        'Upgrade-Insecure-Requests': '1'
    }

    A = requests.session()  # 用一个会话请求
    A.headers = headers

    word = input("请输入关键词：")

    url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&pn={}'  # 请求地址

    tot = count_num(url, A)

    print('经过检测%s类图片共有%d张' % (word, tot))

    numPicture = int(input('请输入想要下载的图片数量: '))

    st = time.time()  # 开始时间
    #下载图片
    DownLoadImg(url, A ,numPicture,word)
    end = time.time()
    # 计算执行时间
    exec_time = end - st
    print("{0}张图片,总共用时" + str(exec_time) + "秒。".format(numPicture))


if __name__ == '__main__':
    main()
